<?php

namespace App\Http\Controllers\System;

use App\Models\System\SysLog;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Auth;
use App\Models\System\Infrastructure;

/**
 * 基础设置逻辑控制器
 *
 * Date: 2018/5/30
 * @author George
 * @package App\Http\Controllers\System
 */
class InfrastructureController extends Controller
{
	/**
	 * 获取系统设置
	 *
	 * Date: 10/05/2018
	 * @author George
	 * @return \Illuminate\Http\JsonResponse
	 */
	public function index()
	{
		$user = Auth::user();
		$settings = Infrastructure::query()->where('company_id', $user->company_id)->first();
		return success($settings);
	}

	/**
	 * 创建公司的基础设置
	 *
	 * Date: 10/05/2018
	 * @author George
	 * @param Request $request
	 * @return \Illuminate\Http\JsonResponse
	 */
	public function store(Request $request)
	{
		$attributes = $this->validate($request, [
			'fingerprint' => 'required',
			'contract' => 'required',
			'internship' => 'required',
			'absenteeism' => 'required',
			'earlier' => 'required',
			'late' => 'required',
			'continuous' => 'required',
		]);

		$user = Auth::user();
		$count = DB::table('infrastructures')->where('company_id', $user->company_id)->count();

		if ($count > 0) {
			return failed('设置已存在，创建失败');
		}

		$settings = Infrastructure::create($attributes);
        SysLog::log($user,'公司基础设置','创建公司基础设置');
		return stored($settings);
	}

	/**
	 * 更新基础设置
	 *
	 * Date: 10/05/2018
	 * @author George
	 * @param Request $request
	 * @return mixed
	 */
	public function update(Request $request)
	{
		$user = Auth::user();

		if (!$user->isManager()) {
			return failed('无权访问', 403);
		}

		$attributes = $this->validate($request, [
			'fingerprint' => 'required',
			'contract' => 'required',
			'internship' => 'required',
			'absenteeism' => 'required',
			'earlier' => 'required',
			'late' => 'required',
			'continuous' => 'required',
		]);

		$settings = Infrastructure::query()
			->where('company_id', $user->company_id)
			->firstOrFail();
		$settings->update($attributes);
        SysLog::log($user,'公司基础设置','更新公司基础设置');
		return updated($settings);
	}
}
